//
//  KINGPictureView.swift
//  肉荣微博
//
//  Created by king on 15/8/3.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit
import SDWebImage

private let pictureCellWidth = 90
//点击图片按钮通知名字
let KINGStatusCellSelectPictureNotification = "KINGStatusCellSelectPictureNotification"
let KINGStatusCellSelectPictureURLKey = "KINGStatusCellSelectPictureURLKey"
let KINGStatusCellSelectPictureIndexPathKey = "KINGStatusCellSelectPictureIndexPathKey"

class KINGPictureView: UICollectionView {
    //此处不能使用懒加载，因为在调用初始化方法前，所有东西都应该准备好
    private let pictureLayout = UICollectionViewFlowLayout()
    
    var status: KINGStatuses? {
        didSet{
            //这里做一个判断，如果是转发微博的话，显示转发微博的图片
            //在这里对status赋值，不会出现死循环，因为有条件限制
            //如果更改了模型，就可以不用这个了，因为获取URL的时候，会根据不同的status获取到不同的url
            //if status?.retweetedStatus != nil {
            //    status = status?.retweetedStatus
            //}
            
            sizeToFit()
            //卧槽，这里不重新加载数据 ，就出不来方块
            reloadData()
        }
    }
    //当调用sizeToFit的时候，会自动调用这个方法
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    /// 计算picture的大小
    private func calcViewSize() -> CGSize {
        //当有0张图片的时候返回（0， 0）
        pictureLayout.itemSize = CGSize(width: pictureCellWidth, height: pictureCellWidth)
        if status?.getPictureUrls?.count == 0 {
            return CGSizeZero
        }
        //当有一张图片的时候，暂时返回（90, 90）
        //TODO
        if status?.getPictureUrls?.count == 1 {
            return CGSize(width: pictureCellWidth, height: pictureCellWidth)
        }
        
        //当有4 张的时候返回
        if status?.getPictureUrls?.count == 4 {
            return CGSize(width: (pictureCellWidth + Int(statusCellContolMargin)) * 2 - Int(statusCellContolMargin), height: (pictureCellWidth + Int(statusCellContolMargin)) * 2 - Int(statusCellContolMargin))
        }
        
        //其他时候，2、3、5、6、必须要进行判断，否则可能造成程序崩溃、
        if let num = status?.getPictureUrls?.count {
//            return CGSize(width: (pictureCellWidth + Int(statusCellContolMargin)) * 3 - Int(statusCellContolMargin), height: (pictureCellWidth + Int(statusCellContolMargin)) * 3 - Int(statusCellContolMargin))
            //其他的时候
            let row = (num - 1) / 3
            let col = (num < 3) ? num : 3
            return CGSize(width: (pictureCellWidth + Int(statusCellContolMargin)) * col - Int(statusCellContolMargin), height: (pictureCellWidth + Int(statusCellContolMargin)) * (row + 1) - Int(statusCellContolMargin))
        }
        return CGSizeZero
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        //设置数据源
        self.dataSource = self
        //设置代理
        self.delegate = self
        registerClass(KINGPictureCell.self, forCellWithReuseIdentifier: "cell")
        backgroundColor = UIColor.lightGrayColor()
        pictureLayout.itemSize = CGSize(width: 90, height: 90)
        pictureLayout.minimumInteritemSpacing = 0
        pictureLayout.minimumLineSpacing = CGFloat(statusCellContolMargin)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension KINGPictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    //MARK: - UICollectionViewDelegate
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //准备好发送的数据需要将url数组和当前选择indexPath传递进去，因为最开始需要显示点击的图片
        let dict = [KINGStatusCellSelectPictureURLKey:status!.getLargePictureURLs!, KINGStatusCellSelectPictureIndexPathKey: indexPath]
        //发送一个通知，因为如果使用代理或者闭包的话，层次结构比较深，所以使用通知 一步到位
        NSNotificationCenter.defaultCenter().postNotificationName(KINGStatusCellSelectPictureNotification, object: self, userInfo: dict)
        print("发送通知、小伙伴准备接收")
    }
    //获取当前点击cell的frame在父控件中的坐标
    func cellForScreenFrame(indexPath:NSIndexPath) -> CGRect {
        let cell = cellForItemAtIndexPath(indexPath)!
        let rect = convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return rect
    }
    //利用缩略图，计算放大之后的frame，因为缩略图和大图的长宽比是一样的
    func cellForFullScreenFrame(indexPath:NSIndexPath) -> CGRect {
        //获取key
        let key = status!.getPictureUrls![indexPath.item].absoluteString
        //根据key获取图片的缓存
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let height = screenSize.width * scale
        //如果高度超过屏幕高度，就返回00 如果没有就返回值中间位置
        var y:CGFloat = 0
        if height < screenSize.height {
            y = (screenSize.height - height) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: height)
    }
    //MARK: - UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.getPictureUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! KINGPictureCell
        //cell.backgroundColor = UIColor.redColor()
        cell.imageURL = status!.getPictureUrls![indexPath.row]
        
        return cell
    }
}

class KINGPictureCell: UICollectionViewCell {
    var imageURL : NSURL? {
        didSet {
            //absoluteString ：获取url中的字符串
            //pathExtension：获取最后的扩展名
            //lowercaseString： 将扩展名编程小写
            gifImageView.hidden = imageURL?.absoluteString.pathExtension.lowercaseString != "gif"
            iconView.sd_setImageWithURL(imageURL)
            //iconView.image = UIImage(named: "avatar_default_big")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(iconView)
        iconView.ff_Fill(contentView)
        contentView.addSubview(gifImageView)
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[gif]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["gif": gifImageView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[gif]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["gif": gifImageView]))
    }
    
    //懒加载控件
    private lazy var iconView:UIImageView = UIImageView()
    private lazy var gifImageView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
